package com.niiwoo.civet.trade.listener;

import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.request.df.InvestSuccessRequest;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by dell on 2017/12/15.
 */
@Slf4j
@Component
public class InvestEventListener {
	@Autowired
	private TianchengDataFlowService tianchengDataFlowService;

	@RabbitListener(queues = {RabbitConstant.Queue.INVEST_EVENT})
	public void investEventSend(InvestSuccessRequest request, Message message, Channel channel) throws IOException {
		log.info("投资事件推送至天秤" + request);
		Boolean isAck = true;
		try {
			tianchengDataFlowService.investSuccess(request);
			log.info("投资事件推送至天秤成功" + request);
		} catch (BizException e) {
			log.error("投资事件推送至天秤业务异常，request=" + request, e);
		} catch (Exception e) {
			log.error("投资事件推送至天秤调用异常，request" + request, e);
			isAck = false;
			try {
				Thread.sleep(5 * 1000L);
			} catch (Exception expect) {
			}
		} finally {
			if (isAck) {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			} else {
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
			}
		}
	}
}
